/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package NodeManager;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 *
 * @author Sean
 */
public class Node {

    private String _location;
    public String NodeName;

    public Node(String NodeName, String location)
            throws IllegalArgumentException, FileNotFoundException {

        if (location == null) {
            throw new IllegalArgumentException("The location cannot be null.");
        }
        _location = location;

        if (!GetPhysicalNode().exists()) {
//            throw new FileNotFoundException(location + " cannot be found.");
        }

        this.NodeName = NodeName;

    }

    private File GetPhysicalNode(){
        return new File(_location);
    }

    protected boolean NodeAvailable() {
        return GetPhysicalNode().exists();
    }

    public String GetLocation() {
        if (NodeAvailable()) {
            return GetPhysicalNode().getPath();
        } else {
            return null;
        }
    }

    private void SetLocation(String location) throws IllegalArgumentException {
        if (!new File(location).isDirectory()) {
            throw new IllegalArgumentException("Parameter - location - must be a directory.");
        }

        this._location = location;
    }

    protected int GetFileCount() {
        return GetPhysicalNode().listFiles().length;
    }

    // TODO need to use java.nio.file for this:
    // http://java.sun.com/docs/books/tutorial/essential/io/copy.html
    void CopyFileToLocation(File fromFile, boolean overwriteIfExists)
            throws IOException {

        try {

            File toFile = new File(GetPhysicalNode().getPath() + File.separatorChar + fromFile.getName());
            InputStream in = new FileInputStream(fromFile);

            //For Appending...
            //OutputStream out = new FileOutputStream(f2,true);

            // TODO - what if it already exists?

            //Overwriting...
            OutputStream out = new FileOutputStream(toFile);

            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
            System.out.println("File copied.");
        } catch (FileNotFoundException ex) {
            System.out.println(ex.getMessage() + " in the specified directory.");
            System.exit(0);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

    }
}
